var curDg = undefined;
var tabIndex = 0;
var editIndexes = [undefined, undefined];
var paramId;
var editModes = [1, 1]; // 元素一：编辑器/键值对模式；元素二：编辑器模式下数据非/是json格式
var objs = {
	httpParamsWin: $("#httpParamsWin"),
	paramsDgWrap: $("#paramsDgWrap"),
	paramsDg: $("#paramsDg"),
	paramsJsonWrap: $("#paramsJsonWrap"),
	paramsJson: $("#paramsJson"),
	headerDg: $("#headerDg")
};

$(function(){
	$.parser.parse();
	
	curDg = objs.paramsDg;
	loadTable();
	loadData();
});

// 加载请求头/请求参数table
function loadTable() {
	var options = {
		emptyMsg: '暂无数据',
		data:[{}],
		columns:[[
			{field:'param',title:'参数名称',width:'25%',align:'center',editor: {type:'textbox',options:{prompt:'请输入参数名称'}}},
			{field:'value',title:'默认值',width:'35%',align:'center',editor: {type:'textbox',options:{prompt:'请输入默认值'}}},
			{field:'description',title:'描述',width:'30%',align:'center',editor: {type:'textbox',options:{prompt:'请输入默认值'}}},
			{field:'operate',title:'操作',width:'10%',align:'center',formatter:operateFormat}
		]],
		onClickCell: onClickCell
	};
	// 请求参数
	objs.paramsDg.xdatagrid(options);
	// 请求头
	objs.headerDg.xdatagrid(options);
	objs.httpParamsWin.xwindow('center');
}

function operateFormat(value, row, index) {
	return "<a class='link' href='javascript:void(0);' onclick='delRow("+index+")'>&times;</a>";
}

function isJSON(str) {
	if (typeof str == 'string') {
		try {
    		var obj = JSON.parse(str);
    		if (obj && typeof obj == 'object') {
        		return true;
    		} else {
        		return false;
    		}
		} catch(e) {
    		return false;
		}
	}
}

// 加载表格数据
function loadData() {
	$.get(
		baseUrl + '/apiManager/httpParamsAction!findOne.action',
		{
			'dto.apiHttpParams.taskId': taskId
		}, function(data, status, xhr){
			if(status == 'success' && data) {
				paramId = data.paramId;
				var requestArgs = JSON.parse(data.requestArgs),
					requestBody = data.requestBody,
					requestHeaders = JSON.parse(data.requestHeaders);
				if (requestArgs && requestArgs.length) {
					objs.paramsDg.xdatagrid('loadData', requestArgs);
				}
				if (requestBody) {
					if (isJSON(requestBody)) {
						editModes[1] = 2; // json格式
					} else {
						editModes[1] = 1; // 非json格式
					}
					objs.paramsJson.xtextbox('setValue', requestBody);
				}
				if (requestHeaders && requestHeaders.length) {
					objs.headerDg.xdatagrid('loadData', requestHeaders);
				}
				objs.httpParamsWin.xwindow('center');
			}
		}, 'json'
	);
}

// 单元格点击事件
function onClickCell(index, field) {
	if ('operate' == field) {
		delRow(index);
		return;
	}
	var editIndex = editIndexes[tabIndex];
	if (editIndex != index){
		if (endEditing()){
			curDg.xdatagrid('selectRow', index)
					.xdatagrid('beginEdit', index);
			var ed = curDg.xdatagrid('getEditor', {index:index,field:field});
			if (ed){
				($(ed.target).data('textbox') ? $(ed.target).xtextbox('textbox') : $(ed.target)).focus();
			}
			editIndexes[tabIndex] = index;
		} else {
			curDg.xdatagrid('selectRow', editIndex);
		}
	}
}

// 结束编辑
/*function endEditing() {
	var editIndex = editIndexes[tabIndex];
	if (editIndex == undefined){return true}
	if (curDg.xdatagrid('validateRow', editIndex)){
		curDg.xdatagrid('endEdit', editIndex);
		editIndexes[tabIndex] = undefined;
		return true;
	} else {
		return false;
	}
}*/

// tabs选择事件
function onTabsSelect(title,index) {
	tabIndex = index;
	if (0 == index) {
		curDg = objs.paramsDg;
	} else if (1 == index) {
		curDg = objs.headerDg;
	}
}

// 新增一行
/*function addRow() {
	curDg.xdatagrid('appendRow', {});
}*/

// 删除一行
/*function delRow(index) {
	curDg.xdatagrid('deleteRow', index);
}*/

//保存接口
function saveHttpParams() {
	if (undefined != editIndexes[0]) {
		objs.paramsDg.xdatagrid('endEdit', editIndexes[0]);
	}
	if (undefined != editIndexes[1]) {
		objs.headerDg.xdatagrid('endEdit', editIndexes[1]);
	}
	var url = baseUrl + '/apiManager/httpParamsAction!saveOrUpdate.action';
	var data = {};
	if (paramId) {
		data['dto.apiHttpParams.paramId'] = paramId;
	} else {
		data['dto.apiHttpParams.taskId'] = taskId;
	}
  
	var rows;
	if (1 == editModes[0]) {
		rows = objs.paramsDg.xdatagrid('getRows')/*.filter(row => !!row.param)*/;
		data['dto.apiHttpParams.requestBody'] = toJsonData(rows);
	} else {
		var requestBody = objs.paramsJson.xtextbox('getValue');
		rows = toTableData(requestBody);
		data['dto.apiHttpParams.requestBody'] = requestBody;
	}
	data['dto.apiHttpParams.requestArgs'] = JSON.stringify(rows);
	data['dto.apiHttpParams.requestArgsJson'] = JSON.stringify(paramsToJson(rows.filter(row => !!row.param), true));
  
	var headers = objs.headerDg.xdatagrid('getRows')/*.filter(v => !!v.param)*/;
	data['dto.apiHttpParams.requestHeaders'] = JSON.stringify(headers);
  
	$.post(url,data,function(res) {
		if ('success' == res) {
			$.xnotify('保存成功', {type: 'success'});
			objs.httpParamsWin.xwindow('close');
		} else {
			$.xnotify('系统错误！', {type: 'warning'});
		}
	}, 'text');
}

//取消关闭弹窗
function closeWin() {
	objs.httpParamsWin.xwindow('close');
}